<template>
  <div class="learning-assistant-container">
    <!--    <h1 class="page-title">在线学习助手</h1>-->
    <div class="assistant-layout" :class="{ 'notes-hidden': !showNotes }">
      <!-- 左侧历史对话区/侧导航栏 -->
      <div class="sidebar" :class="{ collapsed: sidebarCollapsed }">
        <div class="sidebar-header">
          <a-button
            type="primary"
            class="new-chat-btn"
            block
            v-if="!sidebarCollapsed"
            @click="createNewChat"
          >
            <template #icon><PlusOutlined /></template>
            新建会话
          </a-button>
          <a-button type="primary" class="new-chat-btn" v-else @click="createNewChat">
            <template #icon><PlusOutlined /></template>
          </a-button>
        </div>
        <div class="history-section" v-if="!sidebarCollapsed">
          <!-- 所有会话列表 -->
          <div>
            <div class="history-title">会话列表</div>

            <div
              v-for="session in ChatSession1"
              :key="session.id"
              class="chat-history-item"
              :class="{
                active: String(session.id) === activeSessionId && !batchDeleteMode,
                selected: selectedMessages.includes(String(session.id)),
              }"
              @click="
                batchDeleteMode
                  ? toggleSessionSelection(String(session.id))
                  : switchSession(String(session.id))
              "
            >
              <div class="chat-item-content">
                <a-checkbox
                  v-if="batchDeleteMode"
                  :checked="selectedMessages.includes(String(session.id))"
                  @click.stop
                />
                <span class="chat-title">{{ getSessionTitle(session) }}</span>
              </div>
              <div class="chat-actions" v-if="!batchDeleteMode">
                <EditOutlined
                  class="action-icon"
                  @click.stop="editSessionTitle(String(session.id))"
                />
                <DeleteOutlined
                  class="action-icon"
                  @click.stop="confirmDeleteSession(String(session.id))"
                />
              </div>
            </div>
          </div>
        </div>
        <div class="batch-actions" v-if="!sidebarCollapsed">
          <div v-if="!batchDeleteMode">
            <a-button danger @click="startBatchDelete">批量删除</a-button>
          </div>
          <div v-else class="batch-delete-actions">
            <a-button @click="cancelBatchDelete">取消</a-button>
            <a-button
              type="primary"
              danger
              @click="confirmBatchDelete"
              :disabled="selectedMessages.length === 0"
            >
              确定删除 ({{ selectedMessages.length }})
            </a-button>
          </div>
        </div>

        <!-- 侧边栏收起/展开按钮 -->
        <div class="sidebar-toggle">
          <a-button type="text" @click="toggleSidebar">
            <template #icon>
              <MenuFoldOutlined v-if="!sidebarCollapsed" />
              <MenuUnfoldOutlined v-else />
            </template>
          </a-button>
        </div>
      </div>

      <!-- 中间聊天对话区 - 使用Semi Design的Chat组件 -->
      <div class="chat-container" :class="{ centered: !showNotes }">
        <div class="prompt-selector">
          <div class="center-content">
            <a-button class="prompt-btn" @click="openThePromptModal">
              <template #icon>
                <BookOutlined v-if="!selectedPrompt" />
                <CloseOutlined v-else />
              </template>
              {{ !selectedPrompt ? '选择提示词' : `${selectedPrompt.role}` }}
            </a-button>
            <!--            <a-button class="prompt-btn">
              <template #icon><SaveOutlined /></template>
              保存聊天记录
            </a-button>-->
            <!--            <a-button class="prompt-btn" @click="showShareModal = true">
              <template #icon><ShareAltOutlined /> </template>
              分享问答
            </a-button>-->
            <a-button class="prompt-btn" @click="toggleNotes">
              <template #icon><FileTextOutlined /> </template>
              {{ showNotes ? '关闭笔记' : '打开笔记' }}
            </a-button>
          </div>
        </div>

        <!-- Semi Design Chat组件 -->
        <Chat
          :chatBoxRenderConfig="chatBoxRenderConfig"
          class="semi-chat"
          :chats="messages"
          @chats-change="handleChatsChange"
          @message-send="handleSendMessage"
          :role-config="roleConfig"
          :show-stop-generate="isLoading"
          @stop-generator="handleStopGeneration"
          :placeholder="
            isLoading ? '正在生成回复...' : '输入/切换提示词(Enter=发送，shift+enter=换行)'
          "
          @message-copy="handleCopyMessage"
          @message-good-feedback="handleGoodFeedback"
          @message-bad-feedback="handleBadFeedback"
        >
        </Chat>
      </div>

      <!-- 右侧笔记区 -->
      <div class="notes-container" ref="notesContainer" v-show="showNotes">
        <div class="notes-header">
          <div class="notes-title">笔记</div>
          <div class="notes-actions">
            <a-tooltip title="预览">
              <EyeOutlined class="action-icon" @click="togglePreview" />
            </a-tooltip>
            <a-tooltip title="保存" @click="saveNotes">
              <SaveOutlined class="action-icon" />
            </a-tooltip>
            <a-tooltip title="关闭">
              <CloseOutlined class="action-icon" @click="toggleNotes" />
            </a-tooltip>
          </div>
        </div>

        <div class="notes-content" v-if="!showPreview">
          <md-editor
            v-model:modelValue="notesContent"
            @onChange="handleNotesChange"
            style="height: 100%"
            :toolbars="mdToolbars"
            :preview="!showPreview"
          />
        </div>

        <div class="notes-preview" v-else>
          <md-preview :modelValue="notesContent || '预览区域'" />
        </div>

        <div class="resize-handle" @mousedown="startResizing"></div>
      </div>
    </div>

    <!-- 提示词选择模态框 -->
    <a-modal v-model:open="showPromptModal" title="选择提示词" width="800px">
      <div class="prompt-categories">
        <!-- 科目选择区域 -->
        <div class="subject-tabs">
          <a-tabs v-model:activeKey="selectedSubject" @change="handleSubjectChange">
            <a-tab-pane key="" tab="全部"></a-tab-pane>
            <a-tab-pane
              v-for="subject in promptTypeList"
              :key="subject"
              :tab="subject"
            ></a-tab-pane>
          </a-tabs>
        </div>

        <!-- 提示词卡片展示区域 -->
        <div class="prompt-cards-container">
          <div
            v-for="prompt in filteredPromptList"
            :key="prompt.id"
            class="prompt-card"
            :class="{ active: selectedPrompt?.id === prompt.id }"
            @click="selectPrompt(prompt)"
          >
            <div class="card-header">
              <a-avatar class="card-avatar">{{ prompt.subject?.charAt(0) }}</a-avatar>
              <div class="card-title">{{ prompt.role }}</div>
            </div>
            <div class="card-desc">{{ prompt.effect }}</div>
          </div>
        </div>
      </div>
    </a-modal>

    <!--    &lt;!&ndash; 分享问答模态框 &ndash;&gt;-->
    <!--    <a-modal v-model:open="showShareModal" title="分享问答" width="600px">-->
    <!--      <div class="share-message-list">-->
    <!--        <a-checkbox-group v-model:value="selectedMessages">-->
    <!--          <div class="share-message-item" v-for="(msg, index) in messagesToShare" :key="index">-->
    <!--            <a-checkbox :value="msg.id">-->
    <!--              <div class="share-message-content">-->
    <!--                <div class="share-message-question">{{ msg.question }}</div>-->
    <!--                <div class="share-message-answer">{{ msg.answer.substring(0, 50) }}...</div>-->
    <!--              </div>-->
    <!--            </a-checkbox>-->
    <!--          </div>-->
    <!--        </a-checkbox-group>-->
    <!--      </div>-->
    <!--      <template #footer>-->
    <!--        <a-button @click="cancelShare">取消</a-button>-->
    <!--        <a-button type="primary" @click="confirmShare">分享选中的问答</a-button>-->
    <!--      </template>-->
    <!--    </a-modal>-->

    <!-- 会话标题编辑对话框 -->
    <a-modal
      v-model:open="showEditTitleModal"
      title="编辑会话标题"
      @ok="saveSessionTitle"
      @cancel="cancelEditTitle"
    >
      <a-input v-model:value="editingTitle" placeholder="请输入会话标题" />
    </a-modal>

    <!-- 会话删除确认对话框 -->
    <a-modal
      v-model:open="showDeleteModal"
      title="删除会话"
      @ok="deleteSession"
      @cancel="cancelDelete"
    >
      <p>确定要删除会话 "{{ sessionToDelete?.title }}" 吗？此操作不可逆。</p>
    </a-modal>

    <!-- 批量删除确认对话框 -->
    <a-modal
      v-model:open="showBatchDeleteModal"
      title="批量删除会话"
      @ok="batchDeleteSessions"
      @cancel="cancelBatchDelete"
    >
      <p>确定要批量删除选中的会话吗？此操作不可逆。</p>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { computed, h, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import {
  BookOutlined,
  CalculatorOutlined,
  CloseOutlined,
  DeleteOutlined,
  EditOutlined,
  ExperimentOutlined,
  EyeOutlined,
  FileTextOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  PlusOutlined,
  SaveOutlined,
  ShareAltOutlined,
} from '@ant-design/icons-vue'
import { Chat } from '@kousum/semi-ui-vue'
import { MdEditor, MdPreview, type ToolbarNames } from 'md-editor-v3'
import { message } from 'ant-design-vue'
import 'md-editor-v3/lib/style.css'
import type { ChatBoxRenderConfig } from '@kousum/semi-ui-vue/dist/chat/interface'
import type { Message } from '@douyinfe/semi-foundation/lib/es/chat/foundation'
import { nanoid } from 'nanoid'
import {
  addChatSession,
  batchDeleteChatSession,
  deleteChatSession,
  listChatSessionVoByPage,
  updateChatSession,
} from '@/api/chatSessionController'
import { useLoginUserStore } from '@/store/user'
import dayjs from 'dayjs'
import { listPromptSelfVoByPage } from '@/api/promptSelfController'

// 路由实例
const route = useRoute()

// 笔记内容
const notesContent = ref('# 开始做属于你自己的笔记吧')
// 模态框控制
const showPromptModal = ref(false) //提示词
const showShareModal = ref(false) //分析
const showEditTitleModal = ref(false) //会话标题
const showDeleteModal = ref(false) //删除
const showBatchDeleteModal = ref(false) //批量删除
// 笔记预览控制
const showPreview = ref(false)
// 批量删除会话选择
const selectedMessages = ref<string[]>([])
// 笔记区控制
const showNotes = ref(false)
// 侧边栏折叠控制
const sidebarCollapsed = ref(false)
// 编辑会话标题
const editingTitle = ref('')
// 要删除的会话
const sessionToDelete = ref<API.ChatSessionVO | null>(null)
// 批量删除模式
const batchDeleteMode = ref(false)
// 当前选中的提示词
const selectedPrompt = ref<API.PromptSelfVO | null>(null)
// DOM引用
const notesContainer = ref<HTMLElement | null>(null)
const chatBoxRenderConfig = reactive<ChatBoxRenderConfig>({
  renderChatBoxTitle: (props: any) => h('span', { style: { display: 'none' } }, ''),
  renderChatBoxAvatar: (props: any) => h('span', { style: { display: 'none' } }, ''),
})

//提示词相关
//提示词列表
const promptList = ref<API.PromptSelfVO[]>([])
//提示词科目
const selectedSubject = ref<string>('')
const promptTypeList = computed(() => {
  return [...new Set(promptList.value.map((prompt) => prompt.subject))] //使用Set去重
})

// 筛选后的提示词列表
const filteredPromptList = computed(() => {
  if (!selectedSubject.value) {
    // 如果选择的是"全部"，返回所有提示词
    return promptList.value
  }
  // 否则返回对应科目的提示词
  return promptList.value.filter((prompt) => prompt.subject === selectedSubject.value)
})

// 处理科目选择变化
const handleSubjectChange = (value: string) => {
  selectedSubject.value = value
  // 这里不需要重新获取数据，只需要通过计算属性过滤现有数据
}

const openThePromptModal = async () => {
  // 如果已选中提示词，点击按钮表示取消选择
  if (selectedPrompt.value) {
    selectedPrompt.value = null
    return
  }

  //打开模态框
  await fetchPromptList()
  showPromptModal.value = true
  console.log(promptTypeList.value)
}
//提示词查询
const promptSearchParams = reactive<API.PromptSelfQueryRequest>({
  current: 1,
  pageSize: 20, //固定只能展示10个数据 TODO 瀑布流的效果，往下翻才加载
  subject: '', // 初始化为空，获取所有提示词
})
const fetchPromptList = async () => {
  try {
    const res = await listPromptSelfVoByPage({
      ...promptSearchParams,
    })
    if (res.data.data && res.data.code === 0) {
      promptList.value = res.data.data.records ?? []
      console.log(promptList.value)
    } else {
      message.error('获取提示词失败，请稍后重试')
    }
  } catch (e) {
    message.error('获取提示词失败，请稍后重试')
  }
}

// 选择提示词
const selectPrompt = (prompt: API.PromptSelfVO) => {
  if (prompt.effect) {
    // 关闭模态框
    showPromptModal.value = false
    selectedPrompt.value = prompt
  }
}

// 聊天会话
const ChatSession1 = ref<API.ChatSessionVO[]>([])
const loginUser = useLoginUserStore()
const searchParams = reactive<API.ChatSessionQueryRequest>({
  current: 1,
  pageSize: 10, //固定只能展示10个数据 TODO 瀑布流的效果，往下翻才加载
  userId: loginUser.loginUser.id,
  sortField: 'updateTime',
})

// 当前活跃会话ID
const activeSessionId = ref<string>('')

// 聊天相关
const chatId = ref('')

// 使用提供的Message接口
const messages = ref<Message[]>([
  {
    id: '0',
    role: 'assistant',
    content: '你好！我是你的学习助手，有什么我可以帮助你的吗？',
    createAt: Date.now(),
    status: 'complete' as const,
  },
])

// 获取会话列表数据
const fetchData = async () => {
  try {
    const res = await listChatSessionVoByPage({
      ...searchParams,
    })
    if (res.data.data && res.data.code === 0) {
      ChatSession1.value = res.data.data.records ?? []
      console.log(ChatSession1.value)

      // 如果有数据，设置默认活跃会话
      if (ChatSession1.value.length > 0) {
        const firstSession = ChatSession1.value[0]
        //设置笔记
        notesContent.value = ChatSession1.value[0].notes ?? '# 开始做属于你自己的笔记吧'
        activeSessionId.value = String(firstSession.id)
        chatId.value = activeSessionId.value

        // 使用convertMessages函数转换消息格式
        messages.value = convertMessages(firstSession.messages)
      } else {
        await createNewChat()
      }
    } else {
      message.error('获取会话列表失败!')
    }
  } catch (e) {
    message.error('获取会话列表失败!')
  }
}

// 初始化时间设置
onMounted(() => {
  // 初始化处理，确保消息样式正确
  applyProperStyles()
  fetchData()

  // 处理自动消息
  handleAutoMessage()
})

// 处理自动消息
const handleAutoMessage = () => {
  const autoMessage = route.query.autoMessage as string
  if (autoMessage) {
    // 延迟一点时间确保组件完全加载
    setTimeout(() => {
      handleSendMessage(autoMessage)
    }, 1000)
  }
}

// 应用正确的样式
const applyProperStyles = () => {
  // 延迟一点时间让DOM更新
  setTimeout(() => {
    // 确保底部栏显示
    const bottomSlot = document.querySelector('.semi-chat-box-bottom')
    if (bottomSlot) {
      ;(bottomSlot as HTMLElement).style.display = 'block'
    }

    // 调整内容区域的内边距，避免被底部栏遮挡
    const contentBox = document.querySelector('.semi-chat-box-content')
    if (contentBox) {
      ;(contentBox as HTMLElement).style.paddingBottom = '0'
    }

    // 设置笔记区初始宽度
    if (notesContainer.value && showNotes.value) {
      notesContainer.value.style.width = '400px'
    }

    // 移除可能存在的错误样式
    const chatItems = document.querySelectorAll('.semi-chat-box-content-message-item')
    chatItems.forEach((item) => {
      // 确保背景透明
      ;(item as HTMLElement).style.backgroundColor = 'transparent'
    })
  }, 100)
}

// Chat组件的角色配置
const roleConfig = {
  user: {
    name: '我',
    avatar:
      'https://yuwen-diagnosis-1325795131.cos.ap-guangzhou.myqcloud.com//public/1913835897733287938/avatar.jpg',
  },
  assistant: {
    name: '学习助手',
    avatar: '',
  },
}

const isLoading = ref(false)
let eventSource: EventSource | null = null

// Markdown编辑器工具栏配置
const mdToolbars: ToolbarNames[] = [
  'bold',
  'italic',
  'strikeThrough',
  'title',
  'sub',
  'sup',
  'quote',
  'unorderedList',
  'orderedList',
  'codeRow',
  'code',
  'link',
  'image',
  'table',
  'revoke',
  'next',
  'save',
]

// 示例数据 - 实际项目中应从API获取
const messagesToShare = ref([
  {
    id: '1',
    question: '请帮我解释一下牛顿第二定律',
    answer:
      '牛顿第二定律表述为：物体加速度的大小与作用力成正比，与物体质量成反比，加速度的方向与作用力的方向相同。数学表达式为：F = ma',
  },
  {
    id: '2',
    question: '什么是光合作用？',
    answer:
      '光合作用是绿色植物、藻类和某些细菌利用光能，将二氧化碳和水转化为有机物（如葡萄糖）并释放氧气的过程。',
  },
])

// Chat组件消息变化处理
const handleChatsChange = (chats?: Message[]) => {
  // 同步消息状态（如果需要）
  if (!chats) return
  // 不再直接覆盖messages.value，避免用户消息显示两次
  // console.log('消息已更新', chats)
  // messages.value = chats
}

// 发送消息处理
const handleSendMessage = async (content: string) => {
  if (!content.trim() || isLoading.value) return

  // 添加用户消息到聊天记录
  const userMessageId = nanoid()
  const userMessageObj: Message = {
    id: userMessageId,
    role: 'user',
    content: content.trim(),
    createAt: Date.now(),
    status: 'complete' as const,
  }

  messages.value.push(userMessageObj)

  // 更新当前会话的消息
  const currentSession = ChatSession1.value.find(
    (session) => String(session.id) === activeSessionId.value,
  )

  if (currentSession) {
    currentSession.messages.push(userMessageObj)
  }

  // 添加AI消息占位
  const assistantMessageId = nanoid()
  const assistantMessage: Message = {
    id: assistantMessageId,
    role: 'assistant',
    content: '',
    createAt: Date.now(),
    status: 'loading' as const,
  }

  messages.value.push(assistantMessage)

  // 也添加到当前会话中
  if (currentSession) {
    currentSession.messages.push(assistantMessage)
  }

  // 设置加载状态
  isLoading.value = true

  try {
    // 使用SSE连接后端
    connectSSE(content.trim(), assistantMessageId)
  } catch (error) {
    console.error('发送消息出错:', error)
    // 更新消息状态为错误
    const index = messages.value.findIndex((msg) => msg.id === assistantMessageId)
    if (index !== -1) {
      messages.value[index].content = '抱歉，发生了错误，请稍后再试。'
      messages.value[index].status = 'error' as const

      // 同步更新到会话中
      if (currentSession) {
        const sessionMsgIndex = currentSession.messages.findIndex(
          (msg) => msg.id === assistantMessageId,
        )
        if (sessionMsgIndex !== -1) {
          currentSession.messages[sessionMsgIndex].content = '抱歉，发生了错误，请稍后再试。'
          currentSession.messages[sessionMsgIndex].status = 'error' as const
          currentSession.lastMessage = '抱歉，发生了错误，请稍后再试。'
        }
      }
    }
    message.error('发送消息失败，请稍后再试')
    isLoading.value = false
  }
}

// 使用SSE连接
const connectSSE = (userMessage: string, messageId: string) => {
  // 关闭之前的连接
  if (eventSource) {
    eventSource.close()
  }
  //拼接当前选中的prompt的id至请求
  const promptId = selectedPrompt.value?.id || 0
  console.log(promptId)
  let url = `http://localhost:8123/api/chat/learn_app/chat/sse_Emitter/prompt/rag?message=${encodeURIComponent(userMessage)}&chatId=${chatId.value}&promptId=${promptId}`
  if (promptId !== 0) {
    url = `http://localhost:8123/api/chat/learn_app/chat/sse_Emitter/prompt?message=${encodeURIComponent(userMessage)}&chatId=${chatId.value}&promptId=${promptId}`
  }
  // const url = `http://localhost:8123/api/chat/learn_app/chat/sse_Emitter/prompt/rag?message=${encodeURIComponent(userMessage)}&chatId=${chatId.value}&promptId=${promptId}`
  eventSource = new EventSource(url) ///api/chat/learn_app/chat/sse_Emitter/prompt/rag

  // 保存完整的消息内容，用于显示
  let fullContent = ''

  // 获取当前会话
  const currentSession = ChatSession1.value.find(
    (session) => String(session.id) === activeSessionId.value,
  )

  // 监听消息
  eventSource.onmessage = (event) => {
    const chunk = event.data
    //TODO
    // console.log('收到SSE消息片段:', chunk)

    // 更新消息内容
    const index = messages.value.findIndex((msg) => msg.id === messageId)
    if (index !== -1) {
      // 累加完整内容
      fullContent += chunk

      // 创建新消息对象，更改其状态和内容
      const updatedMessage = {
        ...messages.value[index],
        content: fullContent,
        status: 'incomplete' as const, // 使用incomplete表示打字中状态
      }

      // 更新整个消息数组，触发响应式更新
      messages.value = [
        ...messages.value.slice(0, index),
        updatedMessage,
        ...messages.value.slice(index + 1),
      ]

      // 同步更新到会话中
      if (currentSession) {
        const sessionMsgIndex = currentSession.messages.findIndex((msg) => msg.id === messageId)
        if (sessionMsgIndex !== -1) {
          currentSession.messages[sessionMsgIndex] = {
            ...currentSession.messages[sessionMsgIndex],
            content: fullContent,
            status: 'incomplete' as const,
          }
          currentSession.lastMessage =
            fullContent.substring(0, 50) + (fullContent.length > 50 ? '...' : '')
        }
      }
    }
  }

  // 监听错误
  eventSource.onerror = (error) => {
    console.error('SSE错误:', error)

    // 更新消息状态
    const index = messages.value.findIndex((msg) => msg.id === messageId)
    if (index !== -1) {
      const updatedMessage = {
        ...messages.value[index],
        //TODO 返回的格式
        status: 'complete' as const,
      }

      // 更新整个消息数组
      messages.value = [
        ...messages.value.slice(0, index),
        updatedMessage,
        ...messages.value.slice(index + 1),
      ]

      // 同步更新到会话中
      if (currentSession) {
        const sessionMsgIndex = currentSession.messages.findIndex((msg) => msg.id === messageId)
        if (sessionMsgIndex !== -1) {
          currentSession.messages[sessionMsgIndex] = {
            ...currentSession.messages[sessionMsgIndex],
            status: 'complete' as const,
          }
        }
      }
    }

    // 关闭连接
    eventSource?.close()
    eventSource = null
    isLoading.value = false
  }

  // 监听连接关闭
  eventSource.addEventListener('complete', () => {
    // 更新消息状态
    const index = messages.value.findIndex((msg) => msg.id === messageId)
    if (index !== -1) {
      const updatedMessage = {
        ...messages.value[index],
        status: 'complete' as const,
      }

      // 更新整个消息数组
      messages.value = [
        ...messages.value.slice(0, index),
        updatedMessage,
        ...messages.value.slice(index + 1),
      ]

      // 同步更新到会话中
      if (currentSession) {
        const sessionMsgIndex = currentSession.messages.findIndex((msg) => msg.id === messageId)
        if (sessionMsgIndex !== -1) {
          currentSession.messages[sessionMsgIndex] = {
            ...currentSession.messages[sessionMsgIndex],
            status: 'complete' as const,
          }
        }
      }
    }

    // 关闭连接
    eventSource?.close()
    eventSource = null
    isLoading.value = false
  })
}

// 停止生成
const handleStopGeneration = (msg: any) => {
  // 关闭SSE连接
  if (eventSource) {
    eventSource.close()
    eventSource = null
  }

  // 更新消息状态
  const index = messages.value.findIndex((message) => message.id === msg.id)
  if (index !== -1) {
    messages.value[index].status = 'incomplete' as const
  }

  isLoading.value = false
}

// 创建新会话
const createNewChat = async () => {
  const title = `新会话 ${dayjs().format('YYYY-MM-DD HH:mm')}`
  const res = await addChatSession({
    title: title,
  })
  if (res.data.data && res.data.code === 0) {
    //得到会话Id
    await fetchData()
    chatId.value = res.data.data
  }

  // 创建新的会话对象
  // const newSession: API.ChatSessionVO = {
  //   id: Number(chatId.value),
  //   title: title,
  //   messages: [
  //     {
  //       messageType: 'ASSISTANT',
  //       text: '你好！我是你的学习助手，有什么我可以帮助你的吗？',
  //     },
  //   ],
  // }
  //关闭笔记区
  showNotes.value = false
  // 直接将新会话添加到会话列表的开头
  // ChatSession1.value.unshift(newSession)
  // 设置为当前活跃会话
  // activeSessionId.value = String(newSession.id)
  activeSessionId.value = String(chatId.value)
  // 更新当前消息列表
  // messages.value = convertMessages(newSession.messages)

  // //更新笔记
  // // 查找会话
  // const session = ChatSession1.value.find((s) => String(s.id) === sessionId)
  // //笔记区的更新
  // notesContent.value = await session?.notes ?? ''
  // if (session) {
  //   // 使用convertMessages函数转换消息格式
  //   messages.value = convertMessages(session.messages)
  // }

  message.success('已创建新会话')
}

// 切换笔记预览
const togglePreview = () => {
  showPreview.value = !showPreview.value
}

// 切换笔记区显示
const toggleNotes = () => {
  showNotes.value = !showNotes.value
}

// 切换侧边栏折叠状态
const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value
}

// 切换活跃会话
const switchSession = (sessionId: string) => {
  activeSessionId.value = sessionId
  chatId.value = sessionId

  // 查找会话
  const session = ChatSession1.value.find((s) => String(s.id) === sessionId)
  //笔记区的更新
  notesContent.value = session?.notes ?? '# 开始做属于你自己的笔记吧'
  if (session) {
    // 使用convertMessages函数转换消息格式
    messages.value = convertMessages(session.messages)
  }
}

// 获取会话标题
const getSessionTitle = (session: API.ChatSessionVO) => {
  return session.title || `会话 ${new Date().toLocaleString()}`
}

// 编辑会话标题
const editSessionTitle = (sessionId: string) => {
  const session = ChatSession1.value.find((s) => String(s.id) === sessionId)
  if (session) {
    editingTitle.value = session.title
    showEditTitleModal.value = true
  }
}

// 保存会话标题  editingTitle
const saveSessionTitle = async () => {
  const updateParams = reactive<API.updateChatsessionRequest>({
    id: activeSessionId.value,
    title: editingTitle.value.trim(),
  })
  const session = ChatSession1.value.find((s) => String(s.id) === activeSessionId.value)
  if (session) {
    if (editingTitle.value.trim() !== '') {
      try {
        const res = await updateChatSession({
          ...updateParams,
        })
        if (res.data.data && res.data.code === 0) {
          await fetchData()
          message.success('会话标题已更新')
        } else {
          message.error('会话标题更新失败，请稍后重试')
        }
      } catch (e) {
        message.error('会话标题更新失败，请稍后重试')
      }
    }
  }
  showEditTitleModal.value = false
}

// 取消编辑会话标题
const cancelEditTitle = () => {
  showEditTitleModal.value = false
}

// 确认删除会话 === 打开删除模态框
const confirmDeleteSession = (sessionId: string) => {
  const session = ChatSession1.value.find((s) => String(s.id) === sessionId)
  if (session) {
    sessionToDelete.value = session
    showDeleteModal.value = true
  }
}

// 确认删除会话
const deleteSession = async () => {
  if (sessionToDelete.value) {
    // console.log(sessionToDelete.value?.id)
    //删除会话
    const res = await deleteChatSession({
      id: String(sessionToDelete.value?.id),
    })
    if (res.data.data && res.data.code === 0) {
      message.success('会话已删除')
      //重新获取数据
      await fetchData()
    } else {
      message.error('会话删除失败，' + res.data.msg)
    }
    // 从数组中删除会话
    // ChatSession1.value = ChatSession1.value.filter(
    //   (s) => String(s.id) !== String(sessionToDelete.value?.id),
    // )
    // message.success('会话已删除')
    // 如果删除的是当前活跃会话，切换到第一个可用的会话
    if (String(sessionToDelete.value.id) === activeSessionId.value) {
      if (ChatSession1.value.length > 0) {
        activeSessionId.value = String(ChatSession1.value[0].id)

        // 更新当前消息列表
        switchSession(activeSessionId.value)
      } else {
        // 如果没有会话了，清空消息列表
        messages.value = []
        activeSessionId.value = ''
        chatId.value = ''
      }
    }
  }

  showDeleteModal.value = false
}

// 取消删除会话
const cancelDelete = () => {
  showDeleteModal.value = false
}

// 开始批量删除模式
const startBatchDelete = () => {
  batchDeleteMode.value = true
  selectedMessages.value = []
}

// 确认批量删除
const confirmBatchDelete = () => {
  if (selectedMessages.value.length === 0) {
    message.info('请至少选择一个会话进行删除')
    return
  }
  showBatchDeleteModal.value = true
}

// 取消批量删除
const cancelBatchDelete = () => {
  batchDeleteMode.value = false
  selectedMessages.value = []
  showBatchDeleteModal.value = false
}

// 批量删除会话 =>>>>>>> 最后删除逻辑
const batchDeleteSessions = async () => {
  if (selectedMessages.value.length === 0) {
    message.info('没有选择要批量删除的会话。')
    showBatchDeleteModal.value = false
    return
  }
  try {
    const res = await batchDeleteChatSession(selectedMessages.value)
    if (res.data.data && res.data.code === 0) {
      await fetchData()
      // 如果当前活跃的会话被删除，则切换到第一个可用的会话
      if (selectedMessages.value.includes(activeSessionId.value)) {
        if (ChatSession1.value.length > 0) {
          activeSessionId.value = String(ChatSession1.value[0].id)
          switchSession(activeSessionId.value)
        } else {
          // 如果没有会话了，清空消息列表
          messages.value = []
          activeSessionId.value = ''
          chatId.value = ''
        }
      }

      message.success(`成功删除 ${selectedMessages.value.length} 个会话`)
    } else {
      message.error('批量删除消息失败,' + res.data.msg)
    }
  } catch (e) {
    message.error('批量删除消息失败,' + res.data.msg)
  }
  // // 从数组中批量删除会话
  // ChatSession1.value = ChatSession1.value.filter(
  //   (s) => !selectedMessages.value.includes(String(s.id)),
  // )
  showBatchDeleteModal.value = false
  batchDeleteMode.value = false
  selectedMessages.value = []
}

// 消息转换函数 - 将API.Message转换为Semi UI消息格式
const convertMessages = (apiMessages: API.Message[] | undefined) => {
  if (!apiMessages || apiMessages.length === 0) {
    return [
      {
        id: nanoid(),
        role: 'assistant',
        content: '你好！我是你的学习助手，有什么我可以帮助你的吗？',
        createAt: Date.now(),
        status: 'complete' as const,
      },
    ]
  }

  return apiMessages.map((msg) => ({
    id: nanoid(),
    role: msg.messageType?.toLowerCase() === 'user' ? 'user' : 'assistant',
    content: msg.text || '',
    createAt: Date.now(),
    status: 'complete' as const,
  }))
}

// 切换会话选择状态
const toggleSessionSelection = (sessionId: string) => {
  if (selectedMessages.value.includes(sessionId)) {
    selectedMessages.value = selectedMessages.value.filter((id) => id !== sessionId)
  } else {
    selectedMessages.value.push(sessionId)
  }
}

//保存笔记
const saveNotes = async () => {
  const updateParams = reactive<API.updateChatsessionRequest>({
    id: String(activeSessionId.value),
    notes: notesContent.value,
  })
  try {
    const res = await updateChatSession({
      ...updateParams,
    })
    if (res.data.data && res.data.code === 0) {
      message.success('笔记保存成功!')
    } else {
      message.error('笔记保存失败,' + res.data.msg)
    }
  } catch (e) {
    message.error('笔记保存失败,' + res.data.msg)
  }
}

// 笔记内容变更处理
const handleNotesChange = (content: string) => {
  notesContent.value = content
}

// 调整笔记区宽度
const startResizing = (e: MouseEvent) => {
  e.preventDefault()
  const startX = e.clientX
  let startWidth = 0

  if (notesContainer.value) {
    startWidth = notesContainer.value.offsetWidth
  }

  const handleMouseMove = (e: MouseEvent) => {
    if (!notesContainer.value) return
    const deltaX = e.clientX - startX
    const newWidth = Math.max(300, startWidth - deltaX) // 最小宽度300px
    notesContainer.value.style.width = `${newWidth}px`
  }

  const stopResizing = () => {
    document.removeEventListener('mousemove', handleMouseMove)
    document.removeEventListener('mouseup', stopResizing)
  }

  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', stopResizing)
}

// 消息操作
const handleCopyMessage = (msg: any) => {
  let content = typeof msg.content === 'string' ? msg.content : ''

  // 如果内容是数组类型，提取文本
  if (Array.isArray(msg.content)) {
    for (const item of msg.content) {
      if (item.type === 'text' && item.text) {
        content += item.text
      }
    }
  }

  navigator.clipboard
    .writeText(content)
    .then(() => {
      message.success('复制成功')
    })
    .catch(() => {
      message.error('复制失败')
    })
}

const handleGoodFeedback = (msg: any) => {
  message.success('感谢您的反馈')
}

const handleBadFeedback = (msg: any) => {
  message.info('感谢您的反馈，我们会努力改进')
}

// 分享问答相关方法
// const cancelShare = () => {
//   showShareModal.value = false
//   selectedMessages.value = []
// }
//
// const confirmShare = () => {
//   // 这里应该添加分享问答的逻辑，例如调用API
//   console.log('分享选中的问答:', selectedMessages.value)
//   showShareModal.value = false
//   selectedMessages.value = []
// }

onUnmounted(() => {
  // 关闭SSE连接
  if (eventSource) {
    eventSource.close()
    eventSource = null
  }
})
</script>

<style scoped>
.learning-assistant-container {
  padding: 20px;
  height: calc(100vh - 85px);
  overflow: hidden;
  box-sizing: border-box;
  position: relative;
  animation: fadeIn 0.8s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: bold;
  color: #2d5bff;
}

.assistant-layout {
  display: flex;
  height: calc(100% - 20px);
  background: url('@/assets/BackGround/learnbg.png') no-repeat center center;
  background-size: cover;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
  overflow: hidden;
  position: relative;
  z-index: 1;
  transition: all 0.4s cubic-bezier(0.165, 0.84, 0.44, 1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  animation: slideInUp 0.8s ease-out 0.2s both;
}

.assistant-layout::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.85);
  /*  background: linear-gradient(135deg, rgba(22, 119, 255, 0.1), rgba(114, 46, 209, 0.1));*/
  border-radius: 16px;
  z-index: 0;
}

@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(30px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.assistant-layout.notes-hidden {
  justify-content: center;
}

/* 左侧侧边栏样式 */
.sidebar {
  width: 240px;
  display: flex;
  flex-direction: column;
  border-right: 1px solid rgba(255, 255, 255, 0.2);
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(10px);
  transition: all 0.4s cubic-bezier(0.165, 0.84, 0.44, 1);
  position: relative;
  flex-shrink: 0;
  animation: slideInLeft 0.8s ease-out 0.4s both;
  z-index: 1;
}

@keyframes slideInLeft {
  from {
    opacity: 0;
    transform: translateX(-30px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

.sidebar.collapsed {
  width: 60px;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid #eaeaea;
}

.new-chat-btn {
  background: linear-gradient(135deg, #1677ff, #4096ff);
  border: none;
  border-radius: 12px;
  height: 44px;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(22, 119, 255, 0.3);
  transition: all 0.3s cubic-bezier(0.165, 0.84, 0.44, 1);
  position: relative;
  overflow: hidden;
}

.new-chat-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  transition: left 0.5s ease;
}

.new-chat-btn:hover::before {
  left: 100%;
}

.new-chat-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(22, 119, 255, 0.4);
}

.history-section {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
}

.history-title {
  font-size: 14px;
  color: #888;
  margin: 12px 0 8px;
}

.chat-history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border-radius: 12px;
  margin-bottom: 6px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.165, 0.84, 0.44, 1);
  position: relative;
  overflow: hidden;
  animation: fadeInItem 0.6s ease-out;
  animation-delay: calc(var(--item-index, 0) * 0.1s);
}

.chat-history-item:nth-child(1) {
  --item-index: 0;
}
.chat-history-item:nth-child(2) {
  --item-index: 1;
}
.chat-history-item:nth-child(3) {
  --item-index: 2;
}
.chat-history-item:nth-child(4) {
  --item-index: 3;
}
.chat-history-item:nth-child(5) {
  --item-index: 4;
}

.chat-history-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(22, 119, 255, 0.1), transparent);
  transition: left 0.6s ease;
}

.chat-history-item:hover::before {
  left: 100%;
}

.chat-history-item:hover {
  background: rgba(22, 119, 255, 0.08);
  transform: translateX(5px);
  box-shadow: 0 4px 12px rgba(22, 119, 255, 0.15);
}

.chat-history-item.active {
  background: linear-gradient(135deg, rgba(22, 119, 255, 0.1), rgba(64, 150, 255, 0.1));
  border-left: 4px solid #1677ff;
  box-shadow: 0 4px 12px rgba(22, 119, 255, 0.2);
}

.chat-history-item.selected {
  background: linear-gradient(135deg, rgba(22, 119, 255, 0.1), rgba(64, 150, 255, 0.1));
  border-left: 4px solid #1677ff;
  box-shadow: 0 4px 12px rgba(22, 119, 255, 0.2);
}

@keyframes fadeInItem {
  from {
    opacity: 0;
    transform: translateX(-20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

.chat-item-content {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
  overflow: hidden;
}

.batch-delete-actions {
  display: flex;
  justify-content: space-between;
  gap: 8px;
}

.chat-title {
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chat-actions {
  display: none;
}

.chat-history-item:hover .chat-actions {
  display: flex;
}

.action-icon {
  margin-left: 8px;
  font-size: 14px;
  color: #999;
  cursor: pointer;
}

.action-icon:hover {
  color: #2d5bff;
}

.batch-actions {
  padding: 16px;
  border-top: 1px solid #eaeaea;
  text-align: center;
}

.sidebar-toggle {
  position: absolute;
  right: -15px;
  top: 50%;
  transform: translateY(-50%);
  background-color: #fff;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

/* 中间聊天区样式 */
.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(8px);
  position: relative;
  transition: all 0.4s cubic-bezier(0.165, 0.84, 0.44, 1);
  overflow: hidden;
  max-height: 100%;
  animation: slideInRight 0.8s ease-out 0.6s both;
  z-index: 1;
}

@keyframes slideInRight {
  from {
    opacity: 0;
    transform: translateX(30px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

.chat-container.centered {
  max-width: 800px;
  margin: 0 auto;
}

.prompt-selector {
  padding: 12px 16px;
  border-bottom: 1px solid #eaeaea;
  text-align: center;
}

.center-content {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  gap: 16px;
}

.prompt-btn {
  background: linear-gradient(135deg, rgba(22, 119, 255, 0.1), rgba(64, 150, 255, 0.1));
  border: 1px solid rgba(22, 119, 255, 0.3);
  color: #1677ff;
  border-radius: 20px;
  padding: 8px 16px;
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.165, 0.84, 0.44, 1);
  position: relative;
  overflow: hidden;
}

.prompt-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(22, 119, 255, 0.2), transparent);
  transition: left 0.5s ease;
}

.prompt-btn:hover::before {
  left: 100%;
}

.prompt-btn:hover {
  background: linear-gradient(135deg, rgba(22, 119, 255, 0.2), rgba(64, 150, 255, 0.2));
  border-color: #1677ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(22, 119, 255, 0.3);
}

/* Semi Design Chat 样式调整 */
.semi-chat {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
}

:deep(.semi-chat-box-bottom) {
  display: block !important;
}

:deep(.semi-chat-box-content) {
  padding-bottom: 0 !important;
}

/* 右侧笔记区样式 */
.notes-container {
  width: 900px;
  border-left: 1px solid rgba(255, 255, 255, 0.2);
  display: flex;
  flex-direction: column;
  position: relative;
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(10px);
  flex-shrink: 0;
  animation: slideInRight 0.8s ease-out 0.8s both;
  z-index: 1;
}

.notes-header {
  padding: 12px 16px;
  border-bottom: 1px solid #eaeaea;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.notes-title {
  font-weight: bold;
  color: #333;
}

.notes-actions {
  display: flex;
}

.notes-content,
.notes-preview {
  flex: 1;
  overflow-y: auto;
}

.resize-handle {
  position: absolute;
  left: -5px;
  top: 0;
  width: 10px;
  height: 100%;
  cursor: col-resize;
  z-index: 10;
}

/* 提示词模态框样式 */
.prompt-categories {
  max-height: 500px;
  overflow-y: auto;
}

/* 科目标签页样式 */
.subject-tabs {
  margin-bottom: 20px;
}

/* 提示词卡片容器 */
.prompt-cards-container {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  padding: 0 10px;
}

/* 提示词卡片样式 */
.prompt-card {
  width: 220px;
  padding: 20px;
  border: 1px solid rgba(22, 119, 255, 0.2);
  border-radius: 16px;
  cursor: pointer;
  transition: all 0.4s cubic-bezier(0.165, 0.84, 0.44, 1);
  position: relative;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(5px);
  overflow: hidden;
  animation: fadeInCard 0.6s ease-out;
  animation-delay: calc(var(--card-index, 0) * 0.1s);
}

.prompt-card:nth-child(1) {
  --card-index: 0;
}
.prompt-card:nth-child(2) {
  --card-index: 1;
}
.prompt-card:nth-child(3) {
  --card-index: 2;
}
.prompt-card:nth-child(4) {
  --card-index: 3;
}
.prompt-card:nth-child(5) {
  --card-index: 4;
}

.prompt-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(22, 119, 255, 0.1), transparent);
  transition: left 0.6s ease;
}

.prompt-card:hover::before {
  left: 100%;
}

.prompt-card:hover {
  border-color: #1677ff;
  box-shadow: 0 8px 25px rgba(22, 119, 255, 0.2);
  transform: translateY(-5px) scale(1.02);
}

.prompt-card.active {
  border: 2px solid #1677ff;
  box-shadow: 0 8px 25px rgba(22, 119, 255, 0.3);
  transform: translateY(-5px) scale(1.02);
  background: linear-gradient(135deg, rgba(22, 119, 255, 0.05), rgba(64, 150, 255, 0.05));
}

@keyframes fadeInCard {
  from {
    opacity: 0;
    transform: translateY(20px) scale(0.9);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.card-avatar {
  background: linear-gradient(135deg, #1677ff, #4096ff);
  font-size: 16px;
  font-weight: bold;
  box-shadow: 0 4px 12px rgba(22, 119, 255, 0.3);
  transition: all 0.3s ease;
}

.prompt-card:hover .card-avatar {
  transform: scale(1.1) rotate(5deg);
}

.card-title {
  font-weight: bold;
  font-size: 16px;
}

.card-desc {
  font-size: 13px;
  color: #666;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 分享问答模态框样式 */
.share-message-list {
  max-height: 400px;
  overflow-y: auto;
}

.share-message-item {
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.share-message-question {
  font-weight: bold;
  margin-bottom: 4px;
}

.share-message-answer {
  font-size: 12px;
  color: #666;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .notes-container {
    width: 350px;
  }
}

@media (max-width: 992px) {
  .sidebar {
    width: 200px;
  }

  .notes-container {
    width: 320px;
  }
}
</style>

<style>
/* 确保全局没有不必要的滚动条 */
.learning-assistant-container html,
.learning-assistant-container body {
  height: 100%;
  overflow: hidden;
  margin: 0;
  padding: 0;
}

/* 全局动画效果 */
@keyframes float {
  0%,
  100% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-10px);
  }
}

@keyframes pulse {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0.7;
  }
}

/* 添加浮动动画到主要元素 */
.sidebar-toggle {
  animation: float 3s ease-in-out infinite;
}

.action-icon {
  transition: all 0.3s cubic-bezier(0.165, 0.84, 0.44, 1);
}

.action-icon:hover {
  transform: scale(1.2) rotate(5deg);
  color: #1677ff;
}

/* 笔记区调整手柄动画 */
.resize-handle {
  background: linear-gradient(90deg, transparent, rgba(22, 119, 255, 0.3), transparent);
  transition: all 0.3s ease;
}

.resize-handle:hover {
  background: linear-gradient(90deg, transparent, rgba(22, 119, 255, 0.6), transparent);
  transform: scaleX(1.5);
}

/* 打字机效果光标样式 */
@keyframes blink-cursor {
  0% {
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

/* 确保整个聊天区域正确滚动 */
.chat-container .semi-chat {
  height: 100%;
  overflow: auto;
  max-height: 100%;
}

/* 覆盖Semi Design的默认样式 */
.semi-chat-box-content-message-user .semi-chat-box-content-message-text {
  background-color: #f2f3f5;
  border-radius: 8px;
}

.semi-chat-box-content-message-assistant .semi-chat-box-content-message-text {
  background-color: #ffffff;
  border-radius: 8px;
  border: 1px solid #e6e8eb;
}

.semi-chat-box-content-message-system .semi-chat-box-content-message-text {
  background-color: #f9f9fa;
  border-radius: 8px;
  border: 1px solid #e6e8eb;
  color: #333;
}

/* 强制覆盖所有消息的背景颜色 */
.semi-chat .semi-chat-box-content-message-item {
  background-color: transparent !important;
}

/* 针对错误消息的特殊处理 */
.semi-chat .semi-chat-box-content-message-error .semi-chat-box-content-message-text {
  background-color: #fff2f0 !important;
  border: 1px solid #ffccc7 !important;
  color: #333 !important;
}

/* 针对特殊提示的消息处理 */
.semi-chat .semi-chat-box-content-message-info .semi-chat-box-content-message-text {
  background-color: #f0f5ff !important;
  border: 1px solid #d6e4ff !important;
  color: #333 !important;
}
</style>
